package com.neuedu.controller;

import com.neuedu.bean.DeliveryAddress;
import com.neuedu.common.R;
import com.neuedu.service.DeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
// 2. 设置该模块的请求路径，如/user
@RequestMapping("/address")
// 3. 解决跨域
@CrossOrigin(origins = "http://localhost:8081")
public class DeliveryAddressController {

    @Autowired
    private DeliveryAddressService deliveryAddressService;

    @GetMapping("/listDeliveryAddressByUserId/{userId}")
    public R listDeliveryAddressByUserId(@PathVariable("userId") String userId) {

        List<DeliveryAddress> deliveryAddresses = deliveryAddressService.listDeliveryAddressByUserId(userId);

        return R.ok().data(deliveryAddresses);
    }
    @GetMapping("/getDeliveryAddressById/{daId}")
    public R getDeliveryAddressById(@PathVariable("daId") Integer daId) {

        DeliveryAddress deliveryAddress = deliveryAddressService.getDeliveryAddressById(daId);

        return R.ok().data(deliveryAddress);
    }
    @PostMapping("/removeDeliveryAddress/{daId}")
    public R removeDeliveryAddress(@PathVariable("daId") Integer daId) {

        int i = deliveryAddressService.removeDeliveryAddress(daId);
        return i == 1 ? R.ok() : R.error();
    }
    @PostMapping("/saveDeliveryAddress/{deliveryAddress}")
    public ResponseEntity<R> saveDeliveryAddress(@RequestBody DeliveryAddress deliveryAddress) {
        int i = deliveryAddressService.saveDeliveryAddress(deliveryAddress);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "http://localhost:8081");
        return i == 1 ? ResponseEntity.ok().headers(headers).body(R.ok()) : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).headers(headers).body(R.error());
    }
    @PostMapping("/updateDeliveryAddress/{deliveryAddress}")
    public R updateDeliveryAddress(@RequestBody DeliveryAddress deliveryAddress) {

        int i = deliveryAddressService.updateDeliveryAddress(deliveryAddress);

        return i == 1 ? R.ok() : R.error();
    }
    // 处理 OPTIONS 请求
    @RequestMapping(value = "/saveDeliveryAddress", method = RequestMethod.OPTIONS)
    public void handleOptionsSaveDeliveryAddress() {
        // 不需要返回任何内容，只需处理 OPTIONS 请求
    }

    @RequestMapping(value = "/updateDeliveryAddress", method = RequestMethod.OPTIONS)
    public void handleOptionsUpdateDeliveryAddress() {
        // 不需要返回任何内容，只需处理 OPTIONS 请求
    }
}
